package saucaca.Adapter;

import java.util.ArrayList;

import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.R;

import org.json.JSONException;

import saucaca.Adapter.SongAdapter.ViewHolder;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.HomeData;
import saucaca.Object.PlaylistObject;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class PlaylistAdapter extends BaseAdapter{
	Context context;
	ArrayList<PlaylistObject> listPlaylist;
	PopupMenu menuPop = null;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	PlaylistObject playlistObject;
	public PlaylistAdapter(Context context, ArrayList<PlaylistObject> listPlaylist) {
		this.context = context;
		this.listPlaylist = listPlaylist;
		options = new DisplayImageOptions.Builder().showImageOnFail(R.drawable.ic_default).showStubImage(R.drawable.ic_default).showImageForEmptyUri(R.drawable.ic_default)
				.cacheInMemory().cacheOnDisc().build();

	}

	@Override
	public int getCount() {
		return listPlaylist.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}	
	class ViewHolder {
		TextView playlistName;
		TextView playlistTotalSong;
		ImageView imageView;
		ImageButton popup_menu;
	}

	@SuppressLint({ "NewApi", "ViewHolder" })
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		LayoutInflater inflater = LayoutInflater.from(context);
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.item_playlist, null);
			holder.playlistName = (TextView) convertView.findViewById(R.id.song_title);
			holder.playlistTotalSong = (TextView) convertView.findViewById(R.id.song_artist);
			holder.imageView = (ImageView) convertView.findViewById(R.id.playlist_pic);
			holder.popup_menu = (ImageButton) convertView.findViewById(R.id.playlist_popup_menu);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		menuPop = new PopupMenu(context, holder.popup_menu);
		menuPop.getMenuInflater().inflate(R.menu.popup_playlist_list, menuPop.getMenu());
		holder.popup_menu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				playlistObject=listPlaylist.get(position);
				menuPop.show();
			}
		});
		playlistObject=listPlaylist.get(position);
		imageLoader.displayImage(playlistObject.getAVATAR(), holder.imageView, options);
		holder.playlistName.setText(playlistObject.getTXNAME());
		holder.playlistTotalSong.setText(BaseEngine.convertStringLongtoInteger(playlistObject.getTOTAL_SONG()) + " " + context.getResources().getString(R.string.number_song));
		
		menuPop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				switch (item.getItemId()) {
				case R.id.rename:
					TagName.showToastShort(context, "rename");
					break;
				case R.id.delete:
					deleteDialog(playlistObject);
					break;
				default:
					break;
				}
				return true;
			}
		});

		return convertView;
	}

	public void deleteDialog(final PlaylistObject playlistObject) {
		AlertDialog builder = new AlertDialog.Builder(context).create();
		builder.setMessage("Bạn muốn xóa "+playlistObject.getTXNAME()+"?");
		builder.setCancelable(false);
		builder.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				String[] param={playlistObject.getALBUM_ID()};
				new deleteplaylistService().execute(param);
			}
		});
		builder.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	class deleteplaylistService extends AsyncTask<String[], String, String> {
		ProgressDialog progressDialog = new ProgressDialog(context);
		@Override
		protected String doInBackground(String[]... params) {
			String playId = params[0][0];
			String str = WServiceLib.playlistDelete(playId, "0", PreferenceUtils.getString(context, TagName.KeyPreference_user));
			return str;
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!progressDialog.isShowing())
				progressDialog.show();
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (progressDialog.isShowing())
				progressDialog.hide();
			if (result != null)
				try {
					JsonReader.readHeader(result);
					if(HomeData.headerObject.getCODE().equals("0"))
						new GetPlaylist().execute("");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			
			TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
		}
	}
	
	class GetPlaylist extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.playlist("", "", PreferenceUtils.getString(context, TagName.KeyPreference_user));
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					listPlaylist.clear();
					listPlaylist = JsonReader.listPlaylist(result);
					notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}
}